#!/bin/bash

. ./common.sh

license_file=LICENSE.template
src_dir=./src
src_ext=(cpp hpp)

if [[ ! -f $license_file ]]; then
    echo License file \"$license_file\" not found.
    exit
fi

license=$(cat $license_file)

grep_cmd="grep"
i=0
while [[ ! -z ${src_ext[$i]} ]]; do
    grep_cmd="$grep_cmd -e '${src_ext[$i]}'"
done

# checkUpdate (filename) : bool
# Check if the file must be updated
# Return true if the file needs to be updated, false otherwise.
function checkUpdate ()
{
    fname=$1
    flicense=$(awk -f source-license.awk < $fname)
    
    if [[ "$flicense" != "$license" ]]; then true; else false; fi
}

# updateLicense (filename) : void
# Update the license of 'filename'.
function updateLicense ()
{
    fname=$1
    fcontent=$(cat $fname)
    { echo "$license"; echo "$fcontent" | awk -f source-not-license.awk; } > $fname
}

declare -a sources
i=0

for f in `find $(src_dir) -type f | grep -e '\.in$'`; do
    sources[$i]=$f
    ((i++))
done

for f in `find $(src_dir) -type f | $grep_cmd`; do
    j=0
    found=0
    while [[ ! -z ${sources[$j]} ]]; do
	if [[ "${sources[$j]}" == "$f.in" ]]; then found=1; fi
	((j++))
    done

    if [[ $found == 0 ]]; then
	sources[$i]=$f
	((i++))
    fi
done

i=0
while [[ ! -z ${sources[$i]} ]]; do
    f=${sources[$i]}

    if checkUpdate $f; then
        echo -e "Updating license for \033[32m$f\033[0m..."
        updateLicense $f
    else
        echo -e "Skipping license update for \033[31m$f\033[0m..."
    fi

    ((i++))
done
